<template>
  <el-dropdown trigger="click">
    <div class="avatar">
      <img :src="avatarUrl" alt="头像" />
    </div>
    <template #dropdown>
      <el-dropdown-menu width="100px">
        <el-dropdown-item @click="goUserCentreHandler()">
          <el-icon><User /></el-icon>{{ $t("header.userCenter") }}
        </el-dropdown-item>
        <el-dropdown-item @click="openDrawer('editDateRef')">
          <el-icon><Lock /></el-icon>{{ $t("header.editDate") }}
        </el-dropdown-item>
        <el-dropdown-item divided @click="logout">
          <el-icon><SwitchButton /></el-icon>{{ $t("header.logout") }}
        </el-dropdown-item>
      </el-dropdown-menu>
    </template>
  </el-dropdown>
  <EditDateDrawer ref="editDateRef" />
</template>

<script setup lang="ts">
import { computed, ref } from "vue";
import { useRouter } from "vue-router";
import { useUserStore } from "@/stores/modules/user";
import { ElMessageBox } from "element-plus";
import EditDateDrawer from "./EditDateDrawer.vue";
import { LOGIN_URL } from "@/config";
import { useKeepAliveStore, useTabsStore } from "@/stores";
import { useI18n } from "vue-i18n";

defineOptions({
  name: "Avatar"
});

const router = useRouter();
const useUser = useUserStore();
const useTabs = useTabsStore();
const i18n = useI18n();
const useKeepAlive = useKeepAliveStore();
const avatarUrl = computed(() => useUser.userInfo.avatar || "/images/avatar.jpg");

// 退出登录
const logout = () => {
  ElMessageBox.confirm(i18n.t("golbalMessage.warning3"), i18n.t("golbalMessage.warning4"), {
    confirmButtonText: i18n.t("golbalMessage.yes"),
    cancelButtonText: i18n.t("golbalMessage.cancel"),
    type: "warning"
  }).then(async () => {
    // 1.执行退出登录接口
    useTabs.closeMultipleTab();
    useKeepAlive.setKeepAliveName();
    router.replace(LOGIN_URL);
    useUser.clearCacheHandler();
  });
};

const editDateRef = ref<InstanceType<typeof EditDateDrawer> | null>(null);
const openDrawer = (ref: string) => {
  if (ref == "editDateRef") editDateRef.value?.openDrawer();
};

/**
 * @description 跳转用户中心
 */
const goUserCentreHandler = () => {
  router.push("/userCentre");
};
</script>

<style scoped lang="scss">
.avatar {
  width: 40px;
  height: 40px;
  overflow: hidden;
  cursor: pointer;
  border-radius: 50%;
  img {
    width: 100%;
    height: 100%;
  }
}
</style>
